<template>
  <el-drawer
      :title="title"
      :visible.sync="dialogVisible"
      :size="700"
      @close="close"
    >
    <div class="box-card">
      <el-form ref="elForm" :rules="rules" :model="articleInfo" label-width="90px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="articleInfo.title" />
        </el-form-item>

        <el-form-item label="文章封面" title="picUrl" prop="picUrl">
          <el-upload
            action=""
            :show-file-list="false"
            :http-request='uploadFile'
            :beforeUpload="beforeAvatarUpload"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif"
          >
            <img
              v-if="articleInfo.picUrl"
              :src="articleInfo.picUrl | getImgUrl"
              class="avatar"
            >
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

        <el-form-item label="文章内容" prop="detail">
          <editor v-model="articleInfo.detail" :init="editorInit" />
        </el-form-item>
      </el-form>
    </div>
    <div class="footer">
      <el-button @click="close" size="medium">取消</el-button>
      <el-button type="primary" @click="handelConfirm" size="medium">确定</el-button>
    </div>
  </el-drawer>
</template>
<script>
import Editor from '@tinymce/tinymce-vue'
import { addArticle, updateArticle } from '@/api/articles'
import { uploadImg } from '@/api/files'
import { mapGetters } from 'vuex'
export default {
  name: 'NewsArticle',
  components: {
    Editor
  },
  data () {
    return {
      dialogVisible: false,
      title: '新增文章',
      articleInfo: {
        title: '', // 文章标题
        picUrl: '', // 文章封面
        detail: '', // 文章内容
        wzType: '' // 文章类型
      },
      isEdit: false,
      rules: {
        title: [
          {
            required: true,
            message: '请输入文章标题',
            trigger: 'blur'
          }
        ],
        picUrl: [
          {
            required: true,
            message: '请上传文章封面',
            trigger: 'change'
          }
        ],
        detail: [
          {
            required: true,
            message: '请输入文章内容',
            trigger: 'blur'
          }
        ]
      },
      editorInit: {
        language: 'zh_CN',
        height: 500,
        convert_urls: false,
        plugins: ['advlist anchor autolink code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
        images_upload_handler: async function (blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          const { url } = await uploadImg(formData, { fileSize: blobInfo.blob().size })
          success(process.env.VUE_APP_BASE_API + '/file/resource/' + url)
        }
      },
      id: null
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  mounted () {},
  methods: {
    async isShow (wzType, data, isEdit = false) {
      if (!wzType) throw new Error('请传入文章类型')
      this.dialogVisible = true
      isEdit ? (this.title = '编辑文章') : (this.title = '新增文章')
      this.isEdit = isEdit
      this.articleInfo.wzType = wzType
      await this.$nextTick()
      if (isEdit) {
        const formData = this.articleInfo
        for (const key in formData) {
          formData[key] = data[key]
        }
        this.id = data.id
      }
    },
    beforeAvatarUpload (file) {
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$notify({
          message: '上传文件大小不能超过 5MB!',
          type: 'warning'
        })
      }
      return isLt5M
    },
    // 上传文件
    async uploadFile (files) {
      // FormData 对象
      const form = new FormData()
      // 文件对象
      form.append('file', files.file)
      const { url } = await uploadImg(form, { fileSize: files.file.size })
      this.articleInfo.picUrl = url
    },
    close () {
      this.articleInfo.picUrl = ''
      this.$refs.elForm.resetFields()
      this.dialogVisible = false
    },
    handelConfirm () {
      this.$refs.elForm.validate(async valid => {
        if (!valid) return
        this.isEdit ? (await updateArticle({ ...this.articleInfo, id: this.id }))
          : (await addArticle({ ...this.articleInfo, deptId: this.user.departmentId }))
        this.$notify.success({
          title: `完成${this.title}`
        })
        this.$emit('update:visible')
        this.close()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .box-card {
    margin-bottom: 10px;
    padding-right: 20px;
    width: 100%;
    padding-right: 20px;
  }

  .avatar-uploader ::v-deep .el-upload {
    width: 145px;
    height: 145px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
.footer {
  display: flex;
  justify-content: space-around;
  margin-bottom: 40px;
  padding-left: 80px;
  padding-right: 20px;
  .el-button {
    width: 100%;
  }
}
</style>
